package com.nt.train.service;
import com.nt.train.entity.Goods;
import java.lang.ref.SoftReference;
import java.util.HashMap;
import java.util.Map;
/**
 * @author hlf
 * @version 1.0
 * @date 2022/8/16 17:11
 */
public class GoodsCache {

    private volatile static GoodsCache goodsCache;

    // 将缓存对象存储在软引用中
    private Map<String, SoftReference<Goods>> cache;

    public GoodsCache(){
        this.cache = new HashMap<>();
    }

    public static GoodsCache getGoodsCache() {
        if(goodsCache == null) {
            synchronized (GoodsCache.class){
                if(goodsCache == null){
                    goodsCache = new GoodsCache();
                }
            }
        }
        return goodsCache;
    }


    // 根据id存储缓存Goods对象
    public void setCache(Goods goods) {
        cache.put(goods.getId(), new SoftReference<Goods>(goods));
        System.out.println("添加数据到缓存成功");
    }

    // 根据id从缓存中获取对象
    public Goods getCache(String id) {
        // 根据id，获取缓存对象的软引用
        SoftReference<Goods> softRef = cache.get(id);
        return softRef == null ? null : softRef.get();
    }

    public void delCache(String id) {
        cache.remove(id);
        System.out.println("从缓存删除数据成功");
    }
}